# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase
from collections import defaultdict
from bisect import bisect


class TimeMap:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.value_dict = defaultdict(list)

    def set(self, key: str, value: str, timestamp: int) -> None:
        self.value_dict[key].append((timestamp, value))

    def get(self, key: str, timestamp: int) -> str:
        value_list = self.value_dict[key]
        if len(value_list) == 0:
            return ""

        # 从题意可以，value都是由小写字母组成，长度最长为100，所以101个"z"的字符串是最大值。
        # 这样(timestamp, "z" * 101)的比较结果就由timestamp来决定
        index = bisect(value_list, (timestamp, "z" * 101))

        if index > 0:
            return value_list[index - 1][1]
        else:
            return ""


class Solution(SolutionBase):
    def __init__(self):
        self.time_map = TimeMap()

    # 解题的方法，命名和Leetcode的保持一致即可
    def execute_test(self, input1, input2) -> list[str]:
        ans = [None]
        for i in range(1, len(input1)):
            op = input1[i]
            if op == 'set':
                self.time_map.set(input2[i][0], input2[i][1], input2[i][2])
                ans.append(None)
            if op == 'get':
                result = self.time_map.get(input2[i][0], input2[i][1])
                ans.append(result)

        return ans


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        (["TimeMap", "set", "get", "get", "set", "get", "get"],
         [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]],
         [None, None, "bar", "bar", None, "bar2", "bar2"]),
        (["TimeMap", "set", "set", "get", "get", "get", "get", "get"],
         [[], ["love", "high", 10], ["love", "low", 20], ["love", 5], ["love", 10], ["love", 15], ["love", 20],
          ["love", 25]],
         [None, None, None, "", "high", "high", "low", "low"]
         )
    ]

    for case_item in testcases:
        # 获取测试用的case和期待的执行结果
        input1 = case_item[0]
        input2 = case_item[1]

        expect = case_item[len(case_item) - 1]
        exec_result = solution.execute_test(input1, input2)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

